package com.joelaws.blackberry;

import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.rim.device.api.system.Application;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.MainScreen;

public abstract class BaseScreen extends MainScreen {

	private static final String BASE_URL = "http://www.joelaws.com:8089/";

	public BaseScreen() {

	}

	protected void makeMenu(Menu menu, int instance) {

	}

	protected String[] split(String text, char expr) {
		if (text == null || text.length() == 0) {
			return new String[0];
		}
		int count = 0;
		for (int i = 0; i < text.length(); i++) {
			if (text.charAt(i) == expr) {
				count++;
			}
		}

		String[] array = new String[count + 1];

		int beg = 0;
		count = 0;
		for (int i = 1; i < text.length(); i++) {
			if (text.charAt(i) == expr) {
				array[count] = text.substring(beg, i);
				beg = i + 1;
				i++; // doesnt deal well with back-2-back expr
				count++;
			}
		}
		array[count] = text.substring(beg, text.length());

		return array;
	}

	protected String getString(String url) {
		byte[] data = getData(url);
		StringBuffer raw = new StringBuffer();
		raw.append(new String(data, 0, data.length));
		String result = raw.toString();
		return result;
	}

	protected Bitmap getPicture(String url) {
		byte[] data = getData(url);

		EncodedImage image = EncodedImage.createEncodedImage(data, 0,
				data.length);

		return image.getBitmap();
	}

	protected byte[] getData(final String url) {

		HttpConnection conn = null;
		DataInputStream dis = null;

		try {
			conn = (HttpConnection) Connector.open(BASE_URL + url);

			conn.setRequestMethod(HttpConnection.GET);
			int rc = conn.getResponseCode();
			if (rc != HttpConnection.HTTP_OK) {
				throw new IOException("HTTP response code: " + rc);
			}

			dis = conn.openDataInputStream();

			int len = (int) conn.getLength();
			if (len > 0) {
				byte[] data = new byte[len];
				dis.readFully(data);
				return data;
			} else {
				return null;
			}
		} catch (ClassCastException e) {
			System.err.println(e.toString());
			return null;
		} catch (IOException e) {
			System.err.println(e.toString());
			return null;
		} finally {
			if (dis != null) {
				try {
					dis.close();
				} catch (Exception e) {
					System.err.println(e.toString());
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (Exception e) {
					System.err.println(e.toString());
				}
			}
		}

	}

	protected void pushScreen(BaseScreen screen) {
		synchronized (Application.getEventLock()) {
			UiApplication.getUiApplication().pushScreen(screen);
		}
	}
}
